<script setup>
import {ref, onMounted, computed} from 'vue'
import {Background, Controls, MiniMap} from "@vue-flow/additional-components";
import {MarkerType, useVueFlow, VueFlow} from "@vue-flow/core";
import ItemNode from "components/ItemNode.vue";
import CustomEdge from "components/CustomEdge.vue";
import '../css/taskflow.css'
import UploadImage from "components/UploadImage.vue";
import {Dialog, Notify} from "quasar";

// vue flow 事件
const {addNodes, setNodes, removeNodes} = useVueFlow()
const {addEdges, setEdges, updateEdge, removeEdges} = useVueFlow()
const {onConnect, onPaneReady, setTransform, onNodeDragStop, toObject} = useVueFlow()

const props = defineProps(['code', 'detail'])
const emitSelf = defineEmits(['onchange'])
const viewCustomer = ref(false)

// 当前编辑的节点数据
let tab = ref('baseinfo')
let checkpoint = {}
let taskinfo = ref({})

onMounted(() => {
})

// vue flow 绑定事件
onConnect((params) => {
  // console.log('connect', params)
  // params
  addEdges({
    source: params.source,
    target: params.target,
    type: 'custom',
    markerEnd: MarkerType.ArrowClosed
  })

  // 改变关系，重新计算workflow
  saveCheckpointFlow()
})

onNodeDragStop((params) => {
  // 不改变关系，不用重新计算workflow
  checkpoint.flow = toObject()
  emitSelf('onchange')
})

// 显示场地的任务
async function handleShow(data) {
  checkpoint = data
  console.log('show flow', checkpoint)
  const flow = checkpoint.flow

  // 清理原始数据
  await removeNodes(toObject().nodes)

  if (flow) {
    // 重新绑定事件
    flow.nodes.forEach(function (node) {
      // console.log('node', node)
      if (node.type === 'custom') {
        node.events = {click: onNodeClick}
      } else {
        node.data = {}
      }
      // TODO：修改节点默认字段
      // console.log(node)
      // if (node.data.content_all_css === undefined) {
      //   node.data.content_all_css = 'info-wrap'
      // }
      // node.data.image_css = 'bg bg-center'
    })

    setNodes(flow.nodes)
    setEdges(flow.edges)
  } else {
    // 开始节点
    addNodes({
      id: '0000',
      label: checkpoint.name,
      type: 'input',
      position: {x: 100, y: 100},
    })
  }
}

function handleAddNode(data) {
  console.log('add task', data)

  addNodes({
    id: data.code,
    data: data,
    type: 'custom',
    position: {x: 1, y: 100},
    events: {click: onNodeClick}
  })

  // 不改变关系，不用重新计算workflow
  checkpoint.flow = toObject()
  emitSelf('onchange')
}

defineExpose({
  handleShow,
  handleAddNode,
})

///////

// 任务选中
function onNodeClick(node) {
  // console.log('on node click', node)
  // node.node.position.x = 0
  taskinfo.value = node.node.data
  tab.value = 'baseinfo'
  viewCustomer.value = true
}

function onRemoveNode() {
  console.log('remove', taskinfo.value.code)
  Dialog.create({
    title: '提示',
    message: '你确定要删除吗？',
    cancel: true,
    persistent: true
  }).onOk(() => {
    // 删除节点
    removeNodes(taskinfo.value.code)

    // 改变关系，重新计算workflow
    saveCheckpointFlow()

    //
    viewCustomer.value = false
  })
}

function onSaveNodeInfo() {
  console.log('onSaveNodeInfo')
  saveCheckpointFlow()
  viewCustomer.value = false
}


function saveCheckpointFlow() {
  //   11.13  提交数据时统一计算workflow

  // 保存用户操作的节点
  checkpoint.flow = toObject()

  // 改变节点间关系，重新计算workflow
  // checkpoint.workflow = {}
  // formatCheckpointFlow(checkpoint)

  emitSelf('onchange')
}

function loadCheckpointGPS() {
  console.log('checkpoint gps', checkpoint.gps, taskinfo.value)
  taskinfo.value.gps = checkpoint.gps
}

const publishedTaskImageList = computed({
  get() {
    if (taskinfo.value.front_image_list !== undefined) {
      return JSON.stringify(taskinfo.value.front_image_list, null, '\t')
    } else {
      return ''
    }
  },
  set(value) {
    // console.log(value)
    try {
      taskinfo.value.front_image_list = JSON.parse(value)
    } catch (e) {
      Notify.create({
        message: 'JSON 错误:' + e
      })
    }
  }
})

</script>

<template>
  <q-page class="q-pa-md">
    <VueFlow class="basicflow" :default-viewport="{ zoom: 1 }" :min-zoom="0.2" :max-zoom="4">
      <Background pattern-color="#aaa" gap="8"/>
      <Controls/>
      <template #node-custom="props">
        <ItemNode v-bind="props" :detail="detail"/>
      </template>
      <template #edge-custom="props">
        <CustomEdge v-bind="props"/>
      </template>
    </VueFlow>

    <q-dialog v-model="viewCustomer">
      <q-card bordered class="my-card">
        <q-tabs
          v-model="tab"
          no-caps
          class="bg-orange text-white shadow-2"
        >
          <q-tab name="baseinfo" label="交互信息"/>
          <q-tab name="images" label="图片信息"/>
          <q-tab name="images_list" label="图片列表"/>
        </q-tabs>

        <q-separator/>

        <q-tab-panels v-model="tab" animated>
          <q-tab-panel name="baseinfo">
            <q-card>
              <q-card-section class="q-pt-md full-width">
                <q-list>
                  <q-item>
                    <q-item-section>
                      <q-input v-model="taskinfo.memo" label="备注"/>
                    </q-item-section>
                  </q-item>

                  <q-item v-if="taskinfo.type!==300">
                    <q-item-section>
                      <q-input :type="taskinfo.type > 200 ? '' : 'textarea'" v-model="taskinfo.content" label="内容"/>
                    </q-item-section>
                  </q-item>

                  <q-item v-if="taskinfo.type<201">
                    <q-item-section>
                      <q-input v-model="taskinfo.content_css" label="文字样式"/>
                      <q-input v-model="taskinfo.content_all_css" label="文字框样式"/>
                    </q-item-section>
                  </q-item>

                  <div v-if="taskinfo.type===101">
                    <q-item>
                      <q-item-section>
                        <q-input v-model="taskinfo.gps" label="GPS">
                          <template v-slot:append>
                            <q-btn round dense flat icon="file_download" @click="loadCheckpointGPS"/>
                          </template>
                        </q-input>
                      </q-item-section>
                    </q-item>

                    <q-item>
                      <q-item-section>
                        <q-input type="number" v-model="taskinfo.range" label="距离范围"/>
                      </q-item-section>
                    </q-item>
                  </div>

                  <div v-if="taskinfo.type===102">
                    <q-item>
                      <q-item-section>
                        <q-input v-model="taskinfo.beacon" label="Beacon编码"/>
                      </q-item-section>
                    </q-item>

                    <q-item>
                      <q-item-section>
                        <q-input type="number" v-model="taskinfo.rssi" label="信号强度"/>
                      </q-item-section>
                    </q-item>
                  </div>

                  <q-item v-if="taskinfo.type===103">
                    <q-item-section>
                      <q-input v-model="taskinfo.confirm" label="确认信息"/>
                    </q-item-section>
                  </q-item>

                  <div v-if="taskinfo.type===104">
                    <q-item>
                      <q-item-section>
                        <q-input v-model="taskinfo.keyname" label="密钥ID"/>
                      </q-item-section>
                    </q-item>
                  </div>

                  <div v-if="taskinfo.type===105">
                    <q-item>
                      <q-item-section>
                        <q-input v-model="taskinfo.answer" label="答案"/>
                        *{K001}表示密钥内容
                      </q-item-section>
                    </q-item>
                  </div>

                  <div v-if="taskinfo.type===106">
                    <q-item>
                      <q-item-section>
                        <q-input v-model="taskinfo.answer" label="二维码内容"/>
                      </q-item-section>
                    </q-item>
                  </div>

                  <div v-if="taskinfo.type===150"> <!--凯撒密码-->
                    <q-item>
                      <q-item-section>
                        <q-input v-model="taskinfo.keyword" type="textarea" label="原文"/>
                      </q-item-section>
                    </q-item>
                  </div>

                  <div v-if="taskinfo.type===201"><!--普通分支-->
                    <q-item>
                      <q-item-section>
                        <q-input v-model="taskinfo.prompt" label="提示信息"/>
                      </q-item-section>
                    </q-item>
                  </div>

                  <div v-if="taskinfo.type===202"><!--正确分支-->
                    <q-item>
                      <q-item-section>
                        <q-input v-model="taskinfo.prompt" label="提示信息"/>
                      </q-item-section>
                    </q-item>
                  </div>

                  <div v-if="taskinfo.type===203"><!--REDO分支-->
                    <q-item>
                      <q-item-section>
                        <q-input v-model="taskinfo.prompt" label="提示信息"/>
                      </q-item-section>
                    </q-item>
                  </div>

                </q-list>
              </q-card-section>
            </q-card>

          </q-tab-panel>

          <q-tab-panel name="images">
            <q-card>
              <q-card-section class="q-pt-md full-width">
                <upload-image v-model="taskinfo.front_image" title="前景图"></upload-image>
                <q-input v-model="taskinfo.front_image_css" label="样式"/>
              </q-card-section>
              <q-card-section class="q-pt-md full-width">
                <upload-image v-model="taskinfo.image" title="背景图"></upload-image>
                <q-input v-model="taskinfo.image_css" label="样式"/>
              </q-card-section>
            </q-card>
          </q-tab-panel>

          <q-tab-panel name="images_list">
            <q-card>
              <q-card-section class="q-pt-md full-width">
                <q-input type="textarea" rows="20" v-model="publishedTaskImageList" label="图片列表"/>
              </q-card-section>
              <q-card-section class="q-pt-md full-width">
                <q-input v-model="taskinfo.front_image_css" label="样式"/>
              </q-card-section>
            </q-card>
          </q-tab-panel>

        </q-tab-panels>

        <q-card-actions align="right">
          <!--          <q-btn color="secondary" @click="onReset">重置</q-btn>-->
          <q-btn color="deep-orange" @click="onRemoveNode">删除</q-btn>
          <q-btn color="primary" @click="onSaveNodeInfo">保存</q-btn>
        </q-card-actions>
      </q-card>
    </q-dialog>

  </q-page>
</template>

<style scoped lang="sass">
.my-card
  width: 100%
  max-width: 900px
</style>
